<template>
	<div class="mainbody">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>系统功能</el-breadcrumb-item>
				<el-breadcrumb-item>地区管理</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="toolbar-box">
			<div class="list-box">
				<div class="l-list">
					<el-button-group>
						<el-button icon="el-icon-plus" @click="$common.linkUrl('/setting/area/edit')">新增</el-button>
						<el-button icon="el-icon-copy-document" @click="showImportDialog=true">导入</el-button>
						<el-button icon="el-icon-delete" @click="deleteCheckAll">删除</el-button>
					</el-button-group>
				</div>
				<div class="r-list">
					<div class="search-box">
						<el-input placeholder="输入关健字" v-model="keyword" @keyup.enter.native="initData" clearable>
							<el-button slot="append" icon="el-icon-search" @click="initData"></el-button>
						</el-input>
					</div>
				</div>
			</div>
		</div>
		
		<div class="content-box">
			<el-card class="tree-card">
				<el-tree ref="treeList" :data="listData" v-loading="loading" node-key="id" show-checkbox check-on-click-node :expand-on-click-node="false">
					<span class="tree-node" slot-scope="{ node, data }">
						<span>{{ data.title }}</span>
						<span class="tools-box">
							<el-input-number size="mini" v-model="data.sortId" @change="editSortId(data.id, data.sortId)" :min="-99999999" :max="99999999"></el-input-number>
							<el-button size="mini" icon="el-icon-edit" @click="$common.linkUrl('/setting/area/edit/'+data.id)"></el-button>
							<el-button size="mini" icon="el-icon-plus" @click="$common.linkUrl('/setting/area/edit?parentId='+data.id)"></el-button>
							<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteItem(data.id)"></el-button>
						</span>
					</span>
				</el-tree>
			</el-card>
		</div>
		
		<el-dialog title="批量导入" :visible.sync="showImportDialog" fullscreen>
			<el-form ref="importForm" :model="importModel" :rules="rules" label-position="right" label-width="120px">
				<el-form-item label="导入说明">
					<p class="grey">批量导入功能非常耗时，请谨慎使用。</p>
					<p class="grey" style="line-height:24px;">请进入 https://github.com/modood/Administrative-divisions-of-China 下载带编码的JSON数据，例如三级联动的：pca-code.json，数据格式如：{"code":"1001","name":"北京"}，将JSON格式数据复制粘贴到以下编辑框内确认导入。</p>
				</el-form-item>
				<el-form-item label="JSON数据" prop="jsonData">
					<el-input type="textarea" :rows="18" v-model="importModel.jsonData" show-word-limit placeholder="JSON地区数据，不可为空"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" icon="el-icon-edit" @click="submitImportDialog">确 定</el-button>
				<el-button type="warning" @click="showImportDialog = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				loading: false,
				showImportDialog: false, //导入窗口
				keyword: '',
				listData: [],
				importModel: {
					jsonData: ''
				},
				rules: {
					jsonData: [
						{ required: true, message: '请输入标准的JSON地区数据', trigger: 'blur' }
					]
				},
			}
		},
		methods: {
			//加载数据
			initData() {
				let _this = this;
				let sendUrl = "/admin/area";
				if (_this.keyword.length > 0) {
				    sendUrl += "?keyword=" + encodeURI(_this.keyword);
				}
				_this.$api.request({
				    url: sendUrl,
				    beforeSend() {
				        _this.loading = true
				    },
				    success(res) {
				        _this.listData = res.data;
				    },
				    error(err) {
				        _this.listData = []
				    },
				    complete() {
				        _this.loading = false
				    }
				});
			},
			//多选删除
			deleteCheckAll() {
				let _this = this; //当前页面
				//拿到选中的数据
				let list = _this.$refs.treeList.getCheckedKeys();
				//检查是否有选中
				if (list.length == 0) {
					_this.$message({ type: 'warning', message: '请选择要删除的记录！' });
					return false;
				}
				//执行删除操作
				_this.$confirm('确认要删除该记录吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					_this.$api.request({
						method: 'delete',
						url: '/admin/area?ids=' + list.toString(),
						loading: true,
						successMsg: '已删除成功',
						success(res) {
						    _this.initData(); //重新加载列表
						}
					})
				}).catch(function () { });
			},
			//单项删除
			deleteItem(val) {
				let _this = this; //当前页面
				//执行删除操作
				_this.$confirm('确认要删除该记录吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					_this.$api.request({
						method: 'delete',
						url: '/admin/area/' + val,
						loading: true,
						successMsg: '已删除成功',
						success(res) {
						    _this.initData();//重新加载列表
						}
					});
				}).catch(function () { });
						
			},
			//排序数字操作
			editSortId(id, sortId) {
				_this.$api.request({
					method: 'patch',
					url: '/admin/area/' + id,
					data: [{ "op": "replace", "path": "/sortId", "value": sortId }],
					success(res) { }
				});
			},
			//确认批量导入
			submitImportDialog() {
				let _this = this;
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['importForm'].validate((valid) => {
						if (valid) resolve()
					});
				});
				Promise.all([f1]).then(() => {
					_this.$api.request({
						method: 'post',
						url: '/admin/area/import',
						data: _this.importModel,
						loading: true,
						successMsg: '批量导入已成功',
						success(res) {
							//初始化数据
							_this.showImportDialog = false;
							_this.importModel.jsonData = '';
							_this.initData();
						}
					});
				});
			},
		},
		created() {
			this.initData();
		}
	}
</script>
